import { useMutation } from '@tanstack/react-query';
import { Button, Form, Input, message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';

import { Logger } from '../useLogger';

interface RandomNumberGeneratorProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const RandomNumberGenerator: React.FC<RandomNumberGeneratorProps> = ({
  visible,
  setVisible,
}) => {
  const [form] = Form.useForm();

  const GenRandomNumber = useMutation({
    mutationFn: (params: any) => api.GenRandom(params),
    onSuccess: (res: any) => {
      message.success('生成成功');
      const generatedData = res.data.results;
      form.setFieldsValue({ results: generatedData });
    },
    onError: (error: any) => {
      Logger(error);
      message.error('生成失败');
    },
  });

  const handleGenerate = () => {
    form.validateFields().then((values) => {
      const { length } = values;
      if (length <= 0) {
        message.error('请输入一个有效的长度！');
      }
      GenRandomNumber.mutate({ length });
      // 模拟生成随机数
      const generatedData = `生成的${length}位随机数`;
      form.setFieldsValue({ results: generatedData });
    });
  };

  const handleCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  const handleOk = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <Modal
      title="生成随机数"
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      footer={[]}
    >
      <Form form={form} preserve={false} style={{ maxWidth: 600, margin: 24 }}>
        <Form.Item
          label="随机数长度"
          name="length"
          rules={[{ required: true, message: '请输入随机数据长度！' }]}
          style={{ display: 'inline-block' }}
        >
          <Input placeholder="请输入长度" type="number" style={{ width: 150 }} />
        </Form.Item>

        <Button type="primary" onClick={handleGenerate} style={{ marginLeft: 16 }}>
          生成
        </Button>

        <Form.Item name="results" label="结果" style={{ marginTop: 12 }}>
          <Input.TextArea rows={4} readOnly />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default RandomNumberGenerator;
